package com.example.teesystem.common.valid;

import com.example.teesystem.common.cache.UserCache;
import lombok.RequiredArgsConstructor;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

@RequiredArgsConstructor
public class CustomValidIdsValidator implements ConstraintValidator<ValidIds, List<Integer>> {
    private int minValue;
    private boolean ifUserId;
    private boolean allowNull;
    
    @Override
    public void initialize(ValidIds constraintAnnotation) {
        this.minValue = constraintAnnotation.minValue();
        this.ifUserId = constraintAnnotation.ifUserId();
        this.allowNull = constraintAnnotation.allowNull();
    }
    
    @Override
    public boolean isValid(List<Integer> value, ConstraintValidatorContext context) {
        if(!this.allowNull && (value == null || value.isEmpty())) {
            return false;
        }
        if(value != null) {
            for(Integer id : value) {
                if(this.ifUserId) {
                    if(!UserCache.userMap.containsKey(id)) {
                        return false;
                    }
                } else {
                    if(id < minValue) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
